#!/bin/bash
# Linux Build Script for Ollama Translator

echo "🚀 Building Ollama Translator for Linux..."

# Check if running on Linux
if [[ "$OSTYPE" != "linux"* ]]; then
    echo "❌ This script must be run on Linux"
    exit 1
fi

# Check dependencies
if ! command -v python3 &> /dev/null; then
    echo "❌ Python 3 not found. Please install Python 3.8+"
    exit 1
fi

# Check for Qt dependencies
if ! dpkg -l | grep -q "libxcb" && ! rpm -q libxcb &> /dev/null; then
    echo "⚠️  libxcb may not be installed. Installing Qt dependencies..."
    
    # Ubuntu/Debian
    if command -v apt &> /dev/null; then
        sudo apt update
        sudo apt install -y libxcb1 libxcb-xinerama0 libxcb-randr0 libxcb-shape0 \
                          libxcb-xfixes0 libxcb-sync1 libxcb-keysyms1 \
                          libxcb-icccm4 libxcb-image0 libxcb-render-util0 \
                          libxcb-xkb1 libxkbcommon-x11-0 libxkbcommon0
    # Fedora/RHEL
    elif command -v dnf &> /dev/null; then
        sudo dnf install -y libxcb libxcb-devel xcb-util xcb-util-devel \
                          libxkbcommon libxkbcommon-x11
    # Arch Linux
    elif command -v pacman &> /dev/null; then
        sudo pacman -S --noconfirm libxcb xcb-util libxkbcommon libxkbcommon-x11
    else
        echo "⚠️  Please install Qt/XCB dependencies manually for your distribution"
    fi
fi

# Create build directories
mkdir -p build_linux dist_linux

# Install dependencies if needed
echo "📦 Installing dependencies..."
python3 -m pip install --upgrade pip
python3 -m pip install requests PyQt6 PyInstaller

# Set Qt platform to xcb for Linux
export QT_QPA_PLATFORM=xcb

# Build using PyInstaller with Linux-specific settings and Fcitx5 plugin
echo "🔨 Building executable with Fcitx5 plugin..."
python3 -m PyInstaller \
    --onefile \
    --noconsole \
    --name "ollama_translate" \
    --workpath build_linux \
    --distpath dist_linux \
    --add-data "README.md:." \
    --hidden-import config_manager \
    --hidden-import ollama_client \
    --hidden-import translator_gui \
    --hidden-import config_window \
    --hidden-import settings_dialog \
    --add-binary "/home/thuan/Applications/ollama_translate/.venv/lib/python3.13/site-packages/PyQt6/Qt6/plugins/platforminputcontexts/libfcitx5platforminputcontextplugin.so:PyQt6/Qt6/plugins/platforminputcontexts" \
    main.py

# Create desktop entry
echo "📋 Creating desktop entry..."
cat > "dist_linux/ollama-translator.desktop" << EOF
[Desktop Entry]
Version=1.0
Type=Application
Name=Ollama Translator
Comment=Translate text using local Ollama service
Exec=/usr/local/bin/ollama_translate
Icon=ollama-translator
Categories=Utility;Office;Translation;
Keywords=translate;translation;ollama;ai;
Terminal=false
StartupWMClass=ollama_translate
EOF

# Create installation script
cat > "dist_linux/install_linux.sh" << 'EOF'
#!/bin/bash
# Linux Installation Script for Ollama Translator

echo "Installing Ollama Translator..."

# Check if Ollama is running
if ! pgrep -x "ollama" > /dev/null; then
    echo "⚠️  Warning: Ollama service is not running"
    echo "Please start Ollama with: systemctl --user start ollama"
    echo "Or manually: ollama serve"
fi

# Check if running as root for system installation
if [ "$EUID" -eq 0 ]; then
    echo "Installing system-wide..."
    
    # Copy executable
    cp "ollama_translate" /usr/local/bin/
    chmod +x /usr/local/bin/ollama_translate
    
    # Copy desktop entry
    cp "ollama-translator.desktop" /usr/share/applications/
    
    # Create icon directory and placeholder icon
    mkdir -p /usr/share/icons/hicolor/256x256/apps/
    
    echo "✅ Installed to /usr/local/bin/ollama_translate"
    echo "✅ Desktop entry created in /usr/share/applications/"
    
else
    echo "Installing for current user..."
    
    # Create local bin directory
    mkdir -p ~/.local/bin
    
    # Copy executable
    cp "ollama_translate" ~/.local/bin/
    chmod +x ~/.local/bin/ollama_translate
    
    # Create local applications directory
    mkdir -p ~/.local/share/applications
    
    # Copy desktop entry
    cp "ollama-translator.desktop" ~/.local/share/applications/
    
    # Update PATH in .bashrc if not already present
    if ! grep -q "~/.local/bin" ~/.bashrc; then
        echo 'export PATH="~/.local/bin:$PATH"' >> ~/.bashrc
    fi
    
    echo "✅ Installed to ~/.local/bin/ollama_translate"
    echo "✅ Desktop entry created in ~/.local/share/applications/"
    echo ""
    echo "Please restart your terminal or run: source ~/.bashrc"
fi

echo ""
echo "Installation complete!"
echo ""
echo "To run the application:"
echo "  ollama_translate"
echo ""
echo "Or find it in your application menu under 'Utility' or 'Office'"
EOF

chmod +x "dist_linux/install_linux.sh"

# Create run script
cat > "dist_linux/run.sh" << 'EOF'
#!/bin/bash
# Run script for Ollama Translator

echo "Starting Ollama Translator..."

# Set Qt platform
export QT_QPA_PLATFORM=xcb

# Check if Ollama is running
if ! pgrep -x "ollama" > /dev/null; then
    echo "⚠️  Warning: Ollama service is not running"
    echo "Please start Ollama before using the translator"
    echo "Run: ollama serve"
    echo ""
fi

# Run the application
./ollama_translate
EOF

chmod +x "dist_linux/run.sh"

# Verify the build
if [ -f "dist_linux/ollama_translate" ]; then
    SIZE=$(du -h "dist_linux/ollama_translate" | cut -f1)
    echo "✅ Build successful!"
    echo "📁 Executable: dist_linux/ollama_translate ($SIZE)"
    echo "📋 Desktop entry: dist_linux/ollama-translator.desktop"
    echo "📦 Installer: dist_linux/install_linux.sh"
    echo ""
    echo "To run the application:"
    echo "  cd dist_linux && ./run.sh"
    echo ""
    echo "To install:"
    echo "  cd dist_linux && ./install_linux.sh"
    echo ""
    echo "For system-wide installation, run the installer as root:"
    echo "  sudo ./install_linux.sh"
else
    echo "❌ Build failed"
    exit 1
fi